package biz.ws.receive;

import api.common.SpringContext;
import api.common.error.MvcErrorHandlerContainer;
import api.common.result.Result;
import biz.ws.ws.Message;
import biz.ws.ws.UserContainer;
import biz.ws.ws.MsgHolder;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @创建人 wsdc
 * @时间 2021/4/2
 * @描述 消息接收和处理的中间 处理
 * <li>    异常处理  不能因为业务的异常导致链接退出
 */
@Component
@Setter
@Getter
public class MessageExecutorContainer {
    @Resource
    private UserContainer container;

    @Resource
    MvcErrorHandlerContainer mvcErrorHandlerContainer;

    private Map<String, MessageExecutor> clientMap = new HashMap();

    {
        SpringContext.register(context -> {
            Map<String, MessageExecutor> beansOfType = context.getBeansOfType(MessageExecutor.class);
            for (MessageExecutor value : beansOfType.values()) {
                clientMap.put(value.type(), value);
            }
        });
    }

    public void onClientMessage(MsgHolder context){
        Exception e0 = null;
        try{
            Message message = context.getMessage();
            String type = message.getType();

            MessageExecutor handler = clientMap.get(type);
            if(handler != null){
                handler.onMessage(context);
                return ;
            }
        }catch (Exception e){
            e0 = e;
        }

        if(e0 != null){
            Result result = mvcErrorHandlerContainer.exception(e0);
            // TODO: 2021/4/2 输出异常信息 ????
        }
    }
}
